/**
 * Video module
 */

import React from 'react';

class Video extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            videoState: 0,
        };
    }
    componentWillMount() {
        this.intervals = (function (me) {
            let fns = [],
                timer = null,
                interval = 200;

            const run = function () {
                for (let i = 0, l = fns.length; i < l; i++) {
                    const fn = fns[i];
                    fn && fn.call(me);
                }
            };

            const init = function () {
                timer = setInterval(run, interval);
            };

            const destroy = function () {
                clearInterval(timer);
                interval = null;
                timer = null;
                fns = null;
                me = null;
            };

            const getIndexByFn = function (fn) {
                fn = fn || function () {};
                return $.inArray(fn, fns);
            };

            const push = function (fn) {
                const index = getIndexByFn(fn);
                if (index === -1) {
                    fns.push(fn);
                }
            };

            const pop = function (fn) {
                const index = getIndexByFn(fn);
                if (index !== -1) {
                    fns.splice(index, 1);
                }
            };

            return {
                init,
                destroy,
                push,
                pop,
            };
        }(this));
        this.resetVideoInterval = 1;
        this.intervals.push(this.checkVideoStatus);
        this.intervals.push(this.checkVideoState);
        this.intervals.push(this.resetVideoDimensions);
    }
    componentDidMount() {
        this.initElements();
        this.intervals.init();
    }

    componentDidUpdate() {
        const widget = this.props.widget;
        // 视频隐藏播放暂停
        if (widget.visible == false) {
            widget.pause = false;
        }
        if (widget.pause) {
            this.elements.video[0].play();
            this.intervals.push(this.checkVideoStatus);
        } else {
            this.elements.video[0].pause();
            this.intervals.pop(this.checkVideoStatus);
        }
        this.intervals.push(this.checkVideoState);
        if (!this.resetVideoInterval) {
            this.intervals.push(this.resetVideoDimensions);
        }
    }
    componentWillUnmount() {
        this.intervals.destroy();
    }
    initElements() {
        const widget = this.props.widget;
        const isPreview = this.props.preview;
        const prefix = isPreview ? 'preview-wgt-id-' : 'wgt-id-';

        this.elements = {
            parent: $(`#${prefix }${widget.id}`).find('.render-video'),
            video: $(this.refs.video),
        };
    }
    checkVideoStatus() {
        const widget = this.props.widget;
        if (widget) {
            if (widget.repeat) {
                this.intervals.pop(this.checkVideoStatus);
            } else {
                const isPaused = this.elements.video[0].paused;
                if (isPaused) {
                    this.intervals.pop(this.checkVideoStatus);
                    widget.pause = false;
                    this.setState({
                        widget,
                    });
                }
                widget.resolved = false;
            }
        }
    }
    checkVideoState() {
        const widget = this.props.widget;
        const element = this.elements.video;
        const length = element[0].buffered.length;
        if (length) {
            this.intervals.pop(this.checkVideoState);
            widget.resolved = true;// 标识视频是否解析完成
            this.setState({
                videoState: 1,
            });
        } else {
            widget.resolved = false;
        }
    }
    resetVideoDimensions() {
        let videoEl = this.elements.video,
            widget = this.props.widget,
            root = this.props.root,
            contentWidth = parseFloat(widget.width),
            contentHeight = parseFloat(widget.height),
            initWidth = 0,
            videoWidth,
            videoHeight;
        if (!videoEl.length) return;
        const width = videoEl.width();
        if (videoEl.width() != 240 && videoEl.width() != 300) {
            this.intervals.pop(this.resetVideoDimensions);
            this.resetVideoInterval = 0;
            widget.width = contentWidth;
            widget.height = contentWidth / videoEl.width() * videoEl.height();
            videoEl.css({
                width: '100%',
                height: '100%',
            });
            if (root) {
                root.setState({
                    selectedWidget: widget,
                });
            }
        }
    }
    render() {
//        var widget = this.state.widget;//替换视频更新的是selectedWidget,替换会导致编辑Ar中的视频地址未更新
        const { widget } = this.props;
        const src = widget.url || widget.action && widget.action.url;
        widget.pause = widget.pause === undefined ? !!widget.auto_play : widget.pause;
        let videoTipNode = '';
        if (!src) {
            videoTipNode = <span style={{ fontSize: '12px', color: 'black', position: 'absolute', left: '50%', top: '50%', marginLeft: '-35px', marginTop: '-9px' }}>{$._('Video resolution failure')}</span>;
        } else if (!widget.resolved) {
            videoTipNode = <span style={{ fontSize: '12px', color: 'white', position: 'absolute', left: '50%', top: '50%', marginLeft: '-35px', marginTop: '-9px' }}>{$._('Video resolution')}</span>;
        } else {
            videoTipNode = <span className={`glyphicon video-control${widget.pause ? ' glyphicon-pause ' : ' glyphicon-play '}`} />;
        }
        return (
          <div className="render-video">
            {videoTipNode}
            <video loop={widget.repeat ? 'loop' : ''} autoPlay={widget.auto_play ? 'autoplay' : ''} src={src} style={{ opacity: widget.opacity }} preload="metadata" className="video-js vjs-default-skin" data-setup="{}" ref="video">
              <source src={src} />
            </video>
          </div>
        );
    }
}
Video.defaultProps = {
    name: "video",
    type: 4,
    width: 240,
    height: 160,
    type_display: $._("Video"),
    icon_class: "icon-movie",
    repeat: 1
}
module.exports = Video;
